import React, { useEffect, useState } from 'react';
import {
  View,
  Image,
  Text,
  Button,
  ScrollView
} from '@tarojs/components';
import Taro, { useDidShow, useRouter, useShareAppMessage } from '@tarojs/taro';
import {
  AtModal
} from 'taro-ui';
import {
  queryTemplatesList,
  queryUserInfo,
  postDyLogin,
  postTmbDyLogin,
  queryUserArchivesList,
  postAddTask,
  queryUserPoints
} from '@/api';
import {
	setStorageSync,
  getStorageSync
} from '@utils/util';
import {
  ModalMakeing,
  ModalMyFace,
  ModalTask,
  ModalTemplate,
  NavBar,
  Double,
  Guide,
  JoinMember
} from '@/components';
import { useDispatch, useSelector } from 'react-redux';
import { updateToken, updateShowTemplates } from '@stores/actions/user';
import './index.scss';

const Home = () => {
  const router = useRouter();
  const dispatch = useDispatch();
  const user = useSelector((state)=>state.user)
  const [showGuide, setShowGuide] = useState(false);
  const [showDouble, setShowDouble] = useState(false);
  const [showMember, setShowMember] = useState(false);
  const { token } = useSelector((state) => state.user);
  const [isLogined, setIsLogined] = useState(false);
  const [statusBarHeight, setStatusBarHeight] = useState(0);
  const [userInfo, setUserInfo] = useState({});
  const [show, setShow] = useState(false);
  const [showMask, setShowMask] = useState(false);
  const [showLogin, setShowLogin] = useState(false);
  const [showTip, setShowTip] = useState(false);
  const [showTemmplate, setShowTemplate] = useState(false);
  const [showMakeing, setShowMakeing] = useState(false);
  const [showMyFace, setShowMyFace] = useState(false);
  const [showTask, setShowTask] = useState(false);
  const [checked, setChecked] = useState(false);
  const [list, setList] = useState([]);
  const [errorsList] = useState([
    {
      id: 0,
      icon: 'https://jala-test-images.sndaurl.cn/images/example_side.png',
      name: '侧面'
    },
    {
      id: 1,
      icon: 'https://jala-test-images.sndaurl.cn/images/example_occlusion.png',
      name: '有遮挡'
    },
    {
      id: 2,
      icon: 'https://jala-test-images.sndaurl.cn/images/example_dark.png',
      name: '光线暗'
    },
    {
      id: 3,
      icon: 'https://jala-test-images.sndaurl.cn/images/example_vague.png',
      name: '模糊'
    }
  ]);
  const [myPortrayList, setMyPortrayList] = useState([]);
  const [portrayId, setPortrayId] = useState(null);
  const [current, setCurrent] = useState(0);
  const [backdropImg, setBackdropImg] = useState('');
  const [template, setTemplate] = useState('');
  const [templateName, setTemplateName] = useState('');
  const [templateUse, setTemplateUse] = useState('');
  const [num, setNum] = useState(1);
  const [leftface, setLeftFace] = useState('');
  const [leftName, setLeftName] = useState('');
  const [rightface, setRightFace] = useState('');
  const [rightName, setRightName] = useState('');
  const [faceType, setFaceType] = useState('leftface');
  const [canSubmit, setCanSubmit] = useState(true);
  const [point, setPoint] = useState(0);

  useEffect(()=>{
    console.log('user', user)
  }, []);

  useEffect(()=>{
    onLoadTemplates();
  }, []);

  useDidShow(() => {
    if (user.showTemmplates) {
      onShowTemplate();
      dispatch(updateShowTemplates(false));
    }
    const app = Taro.getApp()
    if (app.needRelaodFaceprofile) {
      onLoadArchivesList();
      onCloseTemplate();
      app.needRelaodFaceprofile = false;
    }
    let hasGuide = getStorageSync('hasGuide');
    if (hasGuide) {
      setShowGuide(false);
    } else {
      setShowGuide(true);
    }
    Taro.getSystemInfo({
      success: (res) => {
        setStatusBarHeight(res.statusBarHeight)
      }
    });
    // Taro.hideTabBar();
    onLoadUser();
    onLoadPoint();
  });

  const onLoadPoint = () => {
    queryUserPoints({})
      .then(res=>{
        setPoint(res.currentPoint);
      })
  }

  const onLoadUser = () => {
    queryUserInfo()
      .then(res=>{
        if (res.Code == 403) {
          setIsLogined(false)
        } else {
          setIsLogined(true);
          onLoadArchivesList();
          setUserInfo(res);
        }
      })
  }

  const onLoadTemplates = () => {
    queryTemplatesList({})
      .then(res=>{
        setList(res.list);
        let params = router.params;
        console.log('router', router)
        if (params.tmpl_id) {
          let {
            tmpl_name,
            tmpl_id,
            tmpl_img,
            backdrop_img,
            number,
            use_num
          } = params;
          setBackdropImg(backdrop_img);
          setTemplateName(tmpl_name);
          setCurrent(tmpl_id);
          setTemplate(tmpl_img);
          setNum(number);
          setTemplateUse(use_num);
          setShowMyFace(true);
        }
        else {
          setBackdropImg(res.list[0].backdrop_img);
          setTemplate(res.list[0].img);
          setCurrent(res.list[0].id);
          setTemplateName(res.list[0].tmpl_name);
          setTemplateUse(res.list[0].use_num);
        }
      })
  }

  const onChooseTemplate = (id, url, number, tmpl_name, use_num, backdrop_img) => {
    setBackdropImg(backdrop_img);
    setCurrent(id);
    setTemplate(url);
    setNum(number);
    setTemplateName(tmpl_name);
    setTemplateUse(use_num);
  }

  const showMyPortray = () => {
    if (isLogined) {
      Taro.navigateTo({
        url: '/pages/subpages/myportray/index',
      })
    } else {
      setShowLogin(true);
    }
  }

  const showPersonCenter = () => {
    if (isLogined) {
      Taro.navigateTo({
        url: '/pages/mine/index',
      })
    } else {
      setShowLogin(true);
    }
  }

  const onAuthorize = () => {
    if (isLogined) {
      Taro.navigateTo({
        url: '/pages/subpages/task/index'
      })
    } else {
      setShowLogin(true);
    }
  }

  const onGetPhoneNumber = (e) => {
    let {
      detail
    } = e;
    console.log('e', e)
    let params = {};
    Taro.login().then(loginRes => {
      // setCode(loginRes.code);
      params.phoneCode = detail.code;
      params.code = loginRes.code;
      console.log('params', params)
      // doLogin(params);
    });
  }

  const doLogin = (event) => {
    event.stopPropagation();
    if (checked) {
      Taro.login().then(loginRes => {
        let params = {
          code: loginRes.code,
        }
        postTmbDyLogin(params)
          .then(json=>{
            setStorageSync('token', json.token)
            dispatch(updateToken(json.token))
            onLoadUser();
            setShowLogin(false);
            setShowTip(false);
          })
      })
    } else {
      Taro.showToast({
        title: '请先同意并勾选协议',
        icon: 'none'
      });
    }
  }

  const onRejectLogin = () => {
    setShowLogin(false);
    setShowTip(true);
  }

  const onStillReject = () => {
    setShow(false);
    setShowLogin(false);
    setShowTip(false);
  }

  const onChooseProtocol = (event) => {
    event.stopPropagation();
    setChecked(!checked);
  }

  const onLoadArchivesList = () => {
    queryUserArchivesList()
      .then(res => {
        setMyPortrayList(res.list);
        let data = res.list.filter(item=>{
          return item.id === portrayId
        })
        if (data.length === 0) {
          setLeftFace('');
          setLeftName('');
          setPortrayId(null);
          setRightFace('');
          setRightName('');
        }
      })
  }

  const onStart = () => {
    if (token) {
      myPortrayList.length == 0 ? setShowTemplate(true) : setShowMyFace(true);
    } else {
      setShowLogin(true);
    }
  }

  const onChoosePortrayId = (id) => {
    setPortrayId(id);
  }

  const onChooseItem = (e) => {
    onChoosePortrayId(e.id);
    if (faceType == 'leftface') {
      setLeftFace(e.img);
      setLeftName(e.name);
    } else {
      setRightFace(e.img);
      setRightName(e.name);
    }
    setShowMakeing(false);
    setShowMyFace(true);
  }

  const onMakeing = () => {
    let params = {
      template_id: current,
      face_imgs: [leftface],
    }
    if (num == 2) {
      params.face_imgs = [leftface, rightface];
    }
    if (!leftface || (num == 2 && !rightface)) {
      Taro.showToast({
        title: '请选择脸部档案',
        icon: 'none'
      })
      return
    }
    if (canSubmit) {
      setCanSubmit(false)
      postAddTask(params)
        .then(res=>{
          setCanSubmit(true);
          if (res.Code == 452) {
            onOpenTask();
          } else {
            Taro.navigateTo({
              url: `/pages/makeing/index?TaskId=${res.TaskId}`,
            });
          }
        })
        .catch(err=> {
          setCanSubmit(true);
        })
    }
  }

  const onCloseTemplate = () => {
    setShowTemplate(false);
    setShowMyFace(false);
    setShowTask(false);
    setShowMakeing(true);
  }

  const onCloseMakeing = () => {
    setShowTemplate(false);
    setShowTask(false);
    setShowMakeing(false);
    setShowMyFace(true);
  }

  const onShowTemplate = () => {
    setShowTask(false);
    setShowMakeing(false);
    setShowMyFace(false);
    setShowTemplate(true);
  }

  const onAddMakeing = (e) => {
    e.stopPropagation();
    setShowTask(false);
    setShowMakeing(false);
    setShowMyFace(false);
    setShowTemplate(true);
  }

  const onCloseMyFace = () => {
    setShowTemplate(false);
    setShowMyFace(false);
    setShowTask(false);
    setShowMakeing(false);
  }

  const onOpenTask = () => {
    setShowTemplate(false);
    setShowMyFace(false);
    setShowMakeing(false);
    setShowTask(true);
  }

  const onCloseTask = () => {
    setShowTemplate(false);
    setShowMyFace(true);
    setShowMakeing(false);
    setShowTask(false);
  }

  const onShare = () => {
    setShowTemplate(false);
    setShowMyFace(true);
    setShowMakeing(false);
    setShowTask(false);
    setShowDouble(true);
  }

  const onJoin = () => {
    let {
      dy_type
    } = userInfo;
    let shopId = '';
    let couponId = '';
    // dy_v1 对应自然堂官方旗舰店
    // dy_v2 对应自然堂美妆旗舰店
    // dy_v3 对应抖音自然堂男士旗舰店
    // dy_v4 对应自然堂个护旗舰店
    if (dy_type == 'dy_v1') {
      shopId = '12550325';
      couponId = '7306826482163663116';
    }
    if (dy_type == 'dy_v2') {
      shopId = '41964338';
      couponId = '7306826931721601316';
    }
    if (dy_type == 'dy_v2') {
      shopId = '18308067';
      couponId = '7306827867424473380';
    }
    if (dy_type == 'dy_v3') {
      shopId = '91632294';
      couponId = '7306828487422820645';
    }
    tt.openEcShop({
      shopId: shopId,
      tabType: 1,
      success: (res) => {
        console.log('openEcShop', res)
        setShowMember(false)
      },
      fail: (res) => {
        console.log("调用失败", res);
      }
    })
  }

  const showDetail = (url, name, event) => {
    event.stopPropagation();
    Taro.navigateTo({
      url: `/pages/webview/index?url=${url}&name=${name}`
    });
  }

  return (
    <View
      className='home_view'
      style={{
        backgroundImage: `url(${backdropImg})`
      }}
    >
      <View
        className='home_view_status'
        style={{
          height: `${statusBarHeight}px`
        }}
      ></View>
      <View
        className='home_view_main'
        // style={{
        //   paddingTop: `${statusBarHeight}px`
        // }}
      >
        {/* <View className='maskModal' style={{top: `${statusBarHeight + 184}rpx`}}></View> */}
        <View className='home_view_content'>
          <Image
            src='https://jala-test-images.sndaurl.cn/images/LogoBrand.png'
            className='home_view_content_logo'
            mode='aspectFill'
          />
          <View className='home_view_content_action'>
            <View className='home_view_content_action_info'>
              剩余变妆
              <Text className='home_view_content_action_remain'>
                {userInfo?.num ? userInfo?.num > 99 ? '9+' : userInfo?.num : '-'}
              </Text>
              次
            </View>
            <View
              className='home_view_content_action_get'
              onClick={()=>{
                onAuthorize()
              }}
            >
              去获取
              <Image
                src='https://jala-test-images.sndaurl.cn/images/right.png'
                className='home_view_content_action_get_icon'
                mode='aspectFill'
              />
            </View>
          </View>
        </View>
        <View className='home_view_section'>
          <Image
            src={template}
            mode='aspectFill'
            className='home_view_section_img'
          />
        </View>
        <View className='home_view_container'>
          <View
            className='home_view_container_templates'
          >
            {
              list.map(item=>
                <View className='home_view_container_templates_item_key'
                key={item.id}
                onClick={()=>{onChooseTemplate(item.id, item.img, item.number, item.tmpl_name, item.use_num, item.backdrop_img)}}>
                  <View
                    className={`home_view_container_templates_item ${item.id == current ? 'active' : ''}`}
                  >
                    <View className='home_view_container_templates_item_section'>
                      <Image
                        src={item.tmb_img}
                        className='home_view_container_templates_item_img'
                        mode='aspectFill'
                      />
                      <View
                        className='home_view_container_templates_item_text'
                      >
                        {item.tmpl_name}
                      </View>
                    </View>
                  </View>
                </View>
              )
            }
          </View>
          <View className='home_view_container_actions'>
            <View className='home_view_container_actions_item' onClick={()=>{showMyPortray()}}>
              <Image
                src='https://jala-test-images.sndaurl.cn/images/AI.png'
                className='home_view_container_actions_item_icon'
                mode='aspectFill'
              />
              <View className='home_view_container_actions_item_text'>我的写真</View>
            </View>
            <View className='home_view_container_actions_btn' onClick={()=>{onStart()}}>选择模版开启变妆</View>
            <View className='home_view_container_actions_item' onClick={()=>{showPersonCenter()}}>
              <Image
                src='https://jala-test-images.sndaurl.cn/images/userCenter.png'
                className='home_view_container_actions_item_icon'
                mode='aspectFill'
              />
              <View className='home_view_container_actions_item_text'>个人中心</View>
            </View>
          </View>
        </View>
      </View>
      {
        showTip ? (
          <View className='modal_views'>
            <View className='modal_tip'>
              <View className='modal_tip_title'>温馨提示</View>
              <View className='modal_tip_content'>
                为更好的保护您的个人信息安全，需要您阅读并同意
                <Text
                  className='modal_tip_content_link'
                  onClick={(e)=>{showDetail('https://jala-test-images.sndaurl.cn/images/Service.html', '服务协议', e)}}
                >
                  《用户服务协议》
                </Text>
                和
                <Text
                  className='modal_tip_content_link'
                  onClick={(e)=>{showDetail('https://jala-test-images.sndaurl.cn/images/zrtYs.html', '隐私政策', e)}}
                >
                  《隐私政策》
                </Text>。
                我们将严格按照各项条款适用和保护您的个人信息。
              </View>
              <View className='modal_tip_content mb48'>若您“仍不同意”，我们将无法为您提供完整服务。</View>
              <View className='modal_tip_action'>
                <View
                  className='modal_tip_action_item cancel'
                  onClick={()=>{onStillReject()}}
                >
                  仍不同意
                </View>
                <Button
                  data-eventsync="true"
                  className='modal_tip_action_item sure'
                  onClick={(e)=>{doLogin(e)}}
                >
                  同意并登录
                </Button>
              </View>
            </View>
          </View>
        ) : null
      }
      {
        showLogin ? (
          <View className='maskView' onClick={()=>{setShowLogin(false)}}>
            <View className='modal_view' onClick={(e)=>{e.stopPropagation()}}>
              <Image
                src='https://jala-test-images.sndaurl.cn/images/gift.png'
                mode='aspectFill'
                className='modal_view_icon'
              />
              <View className='modal_view_title'>
                <Image
                  src='https://jala-test-images.sndaurl.cn/images/logo.png'
                  className='modal_view_title_logo'
                  mode='aspectFill'
                />
                <Text className='modal_view_title_name'>加入会员 享新人礼</Text>
              </View>
              <View className='modal_view_subtitle'>隐私政策说明</View>
              <View className='modal_view_detail'>
                <Image
                  src={checked ? 'https://jala-test-images.sndaurl.cn/images/checkmark.png' : 'https://jala-test-images.sndaurl.cn/images/unchecked.png'}
                  className='modal_view_detail_icon'
                  onClick={(e)=>{onChooseProtocol(e)}}
                  mode='aspectFill'
                />
                <View className='modal_view_detail_content'>
                  请您仔细阅读
                  <Text
                    className='modal_view_detail_content_link'
                    onClick={(e)=>{showDetail('https://jala-test-images.sndaurl.cn/images/Service.html', '服务协议', e)}}
                  >《用户服务协议》
                  </Text>和
                  <Text
                    className='modal_view_detail_content_link'
                    onClick={(e)=>{showDetail('https://jala-test-images.sndaurl.cn/images/zrtYs.html', '隐私政策', e)}}
                  >《隐私政策》
                  </Text>。我们将申请您的授权，获取您的手机号用于注册自然堂会员，享受相关权益。阅读后请您勾选左侧按钮，并点击 “同意并登录”，即表示您已阅读并同意上述条款。
                </View>
              </View>
              <View className='modal_view_action'>
                {/* <Button
                  data-eventsync="true"
                  className='modal_view_action_login'
                  onClick={(e)=>{doLogin(e)}}
                >
                  同意并登录
                </Button> */}
                <Button
                  data-eventsync="true"
                  className='modal_view_action_login'
                  openType='getPhoneNumber'
                  onGetPhoneNumber={(e)=>{onGetPhoneNumber(e)}}
                >
                  同意并登录
                </Button>
                <View className='modal_view_action_cancel' onClick={()=>{onRejectLogin()}}>不同意</View>
              </View>
            </View>
          </View>
        ) : null
      }
      {
        showTemmplate ? (
          <ModalTemplate
            onClose={()=>{onCloseTemplate()}}
          />
        ) : null
      }
      {
        showMakeing ? (
          <ModalMakeing
            myPortrayList={myPortrayList}
            portrayId={portrayId}
            onChooseItem={(e)=>{onChooseItem(e)}}
            onAdd={(e)=>{onAddMakeing(e)}}
            onClose={()=>{onCloseMakeing()}}
          />
        ) : null
      }
      {
        showMyFace ? (
          <ModalMyFace
            onClose={()=>{onCloseMyFace()}}
            template={template}
            templateName={templateName}
            templateUse={templateUse}
            leftName={leftName}
            rightName={rightName}
            onClick={()=>{
              setShowMyFace(false);
              setShowTask(true);
            }}
            onUpload={(e)=>{
              let type = e.type;
              setFaceType(type);
              setShowMyFace(false);
              setShowMakeing(true);
            }}
            onRemove={(e)=>{
              let type = e.type;
              if (type === 'leftface') {
                setLeftFace('');
                setLeftName('');
              } else {
                setRightName('');
                setRightFace('');
              }
            }}
            current={current}
            num={num}
            leftface={leftface}
            rightface={rightface}
            onMakeing={()=>{onMakeing()}}
            onShare={()=>{onShare()}}
          />
        ) : null
      }
      {
        showTask ? (
          <ModalTask
            point={point}
            userInfo={userInfo}
            showTask={showTask}
            onClose={()=>{onCloseTask()}}
            onClick={()=>{setShowTask(false)}}
          />
        ) : null
      }
      {
        showGuide ? (
          <Guide
            onClose={()=>{setShowGuide(false)}}
          />
        ) : null
      }
      {
        showDouble ? (
          <Double
            onClick={()=>{setShowDouble(false)}}
          />
        ) : null
      }
      {
        showMember ? (
          <JoinMember
            onClose={()=>{setShowMember(false)}}
            onJoin={()=>{onJoin()}}
          />
        ) : null
      }
    </View>
  )
}

export default Home;
